﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AdministracionAreasComunesWeb.Models;
using System.Net;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;

namespace AdministracionAreasComunesWeb.Controllers
{
    public class AreaComunController : Controller
    {
        private List<AreaComun> CrearAreasComunes()
        {            
            HttpWebRequest req = (HttpWebRequest)WebRequest
                .Create("http://localhost:20000/AreasComunesService.svc/AreasComunes");
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string areaComunJson = reader.ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<AreaComun> areaComunObtenida = js.Deserialize<List<AreaComun>>(areaComunJson);

            //AreasComunesWS.AreasComunesServiceClient proxy = new AreasComunesWS.AreasComunesServiceClient();
            List<AreaComun> areascomunes = new List<AreaComun>();
            foreach (AreaComun prop in areaComunObtenida)
            {
                areascomunes.Add(new AreaComun()
                {
                    IdInventario = Convert.ToInt32(prop.IdInventario),
                    Descripcion = prop.Descripcion,
                    Implementos = prop.Implementos
                });
            }
            return areascomunes;   
        }
        private AreaComun ObtenerAreaComun(int idinventario)
        {
            List<AreaComun> areascomunes = (List<AreaComun>)Session["areascomunes"];
            AreaComun model = areascomunes.Single(delegate(AreaComun areacomun)
            {
                if (areacomun.IdInventario == idinventario) return true;
                else return false;
            });
            return model;
        }

        //
        // GET: /AreaComun/
        public ActionResult Index()
        {
            if (Session["areascomunes"] == null)                
                Session["areascomunes"] = CrearAreasComunes();
            List<AreaComun> model = (List<AreaComun>)Session["areascomunes"];
            return View(model);
        }

        //
        // GET: /AreaComun/Details/5
        public ActionResult Details(int id)
        {
            AreaComun model = ObtenerAreaComun(id);
            return View(model);
        }

        //
        // GET: /AreaComun/Create
        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /AreaComun/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                string postdata = "{\"IdInventario\":" + collection["IdInventario"] + ",\"Descripcion\":\"" + collection["Descripcion"] + "\",\"Implementos\":\"" + collection["Implementos"] + "\"}";
                byte[] data = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest req = (HttpWebRequest)WebRequest
                    .Create("http://localhost:20000/AreasComunesService.svc/AreasComunes");
                req.Method = "POST";
                req.ContentLength = data.Length;
                req.ContentType = "application/json";
                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                var res = (HttpWebResponse)req.GetResponse();
                StreamReader reader = new StreamReader(res.GetResponseStream());
                string areaComunJson = reader.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                string msjResultado = js.Deserialize<string>(areaComunJson);

                //AreasComunesWS.AreasComunesServiceClient proxy = new AreasComunesWS.AreasComunesServiceClient();
                //string msjResultado = proxy.CrearAreaComun(int.Parse(collection["IdInventario"]),collection["Descripcion"],collection["Implementos"]);

                if (msjResultado.Equals(""))
                {
                    List<AreaComun> areascomunes = (List<AreaComun>)Session["areascomunes"];
                    areascomunes.Add(new AreaComun()
                    {
                        IdInventario = int.Parse(collection["IdInventario"]),
                        Descripcion = collection["Descripcion"],
                        Implementos = collection["Implementos"]
                    });
                    return RedirectToAction("Index");
                }
                else 
                {
                    ViewData["MsjError"] = "--- ERROR! " + msjResultado;
                    return View();
                }
            }
            catch
            {
                ViewData["MsjError"] = "--- ERROR! Datos incompatibles ---";
                return View();
            }
        }

        
        //
        // GET: /AreaComun/Edit/5 
        public ActionResult Edit(int id)
        {
            AreaComun model = ObtenerAreaComun(id);
            return View(model);
        }

        //
        // POST: /AreaComun/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                //Prueba de Obtencion de alumno via HTTP PUT
                string postdata = "{\"IdInventario\":" + collection["IdInventario"] + ",\"Descripcion\":\"" + collection["Descripcion"] + "\",\"Implementos\":\"" + collection["Implementos"] + "\"}";
                byte[] data = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest req = (HttpWebRequest)WebRequest
                    .Create("http://localhost:20000/AreasComunesService.svc/AreasComunes");
                req.Method = "PUT";
                req.ContentLength = data.Length;
                req.ContentType = "application/json";
                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                var res = (HttpWebResponse)req.GetResponse();
                StreamReader reader = new StreamReader(res.GetResponseStream());
                string areaComunJson = reader.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                string msjResultado = js.Deserialize<string>(areaComunJson);

                //AreasComunesWS.AreasComunesServiceClient proxy = new AreasComunesWS.AreasComunesServiceClient();
                //string msjResultado = proxy.ModificarAreaComun(int.Parse(collection["IdInventario"]),collection["Descripcion"],collection["Implementos"]);

                if (msjResultado.Equals(""))
                {
                    AreaComun model = ObtenerAreaComun(id);
                    model.Descripcion = collection["Descripcion"];
                    model.Implementos = collection["Implementos"];
                    return RedirectToAction("Index");               
                }
                else
                {
                    ViewData["MsjError"] = "--- ERROR! " + msjResultado;
                    return View();
                }
            }
            catch (Exception e)
            {
                ViewData["MsjError"] = "--- Datos incompatibles ---";
                return View();
            }
        }

        //
        // GET: /AreaComun/Delete/5 
        public ActionResult Delete(int id)
        {
            AreaComun model = ObtenerAreaComun(id);
            return View(model);
        }

        //
        // POST: /AreaComun/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                //AreasComunesWS.AreasComunesServiceClient proxy = new AreasComunesWS.AreasComunesServiceClient();
                //string msjResultado = proxy.EliminarAreaComun(id);
                string ruta = "http://localhost:20000/AreasComunesService.svc/AreasComunes/" + id.ToString();
                HttpWebRequest req = (HttpWebRequest)WebRequest
                    .Create(ruta);
                req.Method = "DELETE";
                var res = (HttpWebResponse)req.GetResponse();
                StreamReader reader = new StreamReader(res.GetResponseStream());
                string areaComunJson = reader.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                string msjResultado = js.Deserialize<string>(areaComunJson);

                if (msjResultado.Equals(""))
                {
                    List<AreaComun> areascomunes = (List<AreaComun>)Session["areascomunes"];
                    areascomunes.Remove(ObtenerAreaComun(id));
                    return RedirectToAction("Index");
                }
                else 
                {
                    ViewData["MsjError"] = "--- ERROR! " + msjResultado;
                    return View();
                }
            }
            catch
            {
                ViewData["MsjError"] = "--- ERROR! ";
                return View();
            }
        }
    }
}
